<template>
  <el-select
    v-model="internalValue"
    :loading="loading"
    :placeholder="props.placeholder"
    clearable
    filterable
    :multiple="props.multiple"
    :remote-method="loadOptions"
    @change="(value: number) => emit('update:modelValue', value)"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

const props = defineProps({
  // 远程获取数据的方法，必须返回一个 Promise，Promise 解析后的数据是一个数组
  fetchList: {
    type: Function,
    required: true,
  },
  // 选项对象中作为值的字段名
  valueKey: {
    type: String,
    default: 'id',
  },
  // 选项对象中作为标签的字段名
  labelKey: {
    type: String,
    default: 'name',
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  // 选择器的占位符
  placeholder: {
    type: String,
    default: '请选择',
  },
})
const internalValue = ref(undefined)
const options = ref([])
const loading = ref(false)
const emit = defineEmits(['update:modelValue'])

async function loadOptions(query = '') {
  loading.value = true
  const list = await props.fetchList(query)
  options.value = list.map((item: any) => ({
    value: item[props.valueKey],
    label: item[props.labelKey],
  }))
  loading.value = false
}

onMounted(async () => {
  loadOptions()
})
</script>

<style scoped>
/* 可根据需要添加样式 */
</style>
